<?php
class Form_Detail extends Form_Base
{
    protected $_type;
    protected $_data;
    protected $_group_level;
    protected $_group_count;
    protected $_app_controller;

    public function __construct ($type, $controller)
    {
        $this->_type = $type;
        $this->_data = array();
        $this->_group_level = 0;
        $this->_group_count = array();
        $this->_app_controller = $controller;
    }

    public function set_data ($data)
    {
        $this->_data = $data;
        $this->_group_level = 0;
        $this->_group_count = array();
        return $this;
    }

    public function build_detail ($show_type = 'form', $type = NULL, $group_suffix = NULL, $form_data = NULL)
    {
        $type = empty($type) ? $this->_type : $type;

        $query = DB::select()
            ->from('form_items_config')
            ->where('type', '=', $type)
            ->order_by('sort', 'asc')
            ->execute()
            ->as_array();

        $this->_app_controller->detail_filter_config_data ($query);

        $ul = "<ul class=\"$show_type\">\n";
        foreach ($query as $rs)
        {
            // set value for edit
            if (NULL === $form_data)
                $rs['value'] = Arr::get($this->_data, $rs['input_name']);
            else
                $rs['value'] = Arr::get($form_data, $rs['input_name']);

            if ($show_type == 'group')
                $rs['input_name'] = $rs['input_name'].$group_suffix;
            $input_element = $this->build_input_element($rs, $group_suffix);
$ul .=<<<EOF
<li class="{$rs['class']}">
    <label>{$rs['label']}: </label>
    <span>
        $input_element
    </span>
</li>

EOF;
            
        }

        $ul .= "</ul>\n";

        if ($show_type == 'group')
        {
        }
        else if ($show_type == 'form')
        {
            $buttons = $this->build_buttons('list');
            $ul =<<<EOF
<div class="detailbox">
        <div class="btns">$buttons</div>
        $ul
</div>

EOF;
        }

        return $ul;
    }


    private function build_input_element ($rs, $group_suffix)
    {
        switch ($rs['input_type'])
        {
        case 'text':
            return "{$rs['value']}";
            break;

        case 'hidden':
            return "{$rs['value']}";
            break;

        case 'textarea':
            return '<pre>'.$rs['value'].'</pre>';
            break;

        case 'editor':
            return $rs['value'];
            break;

        case 'select':
            $options = $this->build_select_options ($rs['options'], $rs['value'], $rs['param']);
            return $options;
            break;

        case 'images' :
            $imgs = '';
            if (is_string($rs['value']))
                $rs['value'] = explode('|', $rs['value']);
            if(!empty($rs['value'])){
                foreach ($rs['value'] as $src)
                {
                    $imgs .= '<div class="imgbox"><img class="upimg" src="'.$src.'"></div>';

                }

                return '<div class="imgbox_'.$rs['input_name'].'">'.$imgs.'</div>';
            }else{
                return "";
            }
            break;

        case 'file' :

            if (! empty($rs['value']))
            {
                $file_value = '<div class="imgbox"><p><a href="'.$rs['value'].'">点击打开</a></p></div>';
                return '<div class="imgbox_'.$rs['input_name'].'">'.$file_value.'</div>';
            }
            else
            {
                return '暂无文件';
            }
            break;

        case 'radio':
            $options = $this->build_input_radio ($rs);
            return $options;
            break;

        case 'date':
            return '<span class="date">'.$rs['value'].'</span>';
            break;

        case 'group':
            $str = '';
            $index = 0;
            $this->_group_level += 1;
            $grp_type_name = $rs['param'];
            foreach ($rs['value'] as $val)
            {
                $this->record_group_current_count();
                $suffix = $this->current_group_suffix();

                $str .= self::build_detail('group', $grp_type_name, $suffix, $val);
                $index++;
            }
            $this->_group_level -= 1;
            return $str;
            break;

        case 'images' :
            return Form_Element_Images::current()->build_show($rs);
            break;

        default:
            return '';
            break;
        }
    }

    private function build_input_radio ($item)
    {
        $inputs = array();

        $optstr = $item['options'];
        $optval = $item['value'];
        $opts = explode("\n", $optstr);
        $options = array();
        foreach ($opts as $rs)
        {
            if (empty($rs))
                continue;

            $items = explode('|', $rs);
            if (count($items) == 2 && ! empty($items[1]))
            {
                $value = $items[0];
                $label = $items[1];

                $options[] = array('label' => $label, 'value' => $value);
            }
        }


        foreach ($options as $opt)
        {
            $checked  = $optval !== NULL && $optval == $opt['value'] ?  'checked="checked"' : '';
            if ($checked)
                return $opt['label'];
        }

        return '';
    }

    private function build_select_options ($optstr, $optval, $param)
    {
        if (preg_match('/^\s*function:(.+)$/', $optstr, $m))
        {
            $func = $m[1];
            return self::build_select_options_dynamic($func, $optval, $param);
        }

        $opts = explode("\n", $optstr);
        $options = array();
        foreach ($opts as $rs)
        {
            if (empty($rs))
                continue;

            $items = explode('|', $rs);
            if (count($items) == 2 && ! empty($items[1]))
            {
                $value = $items[0];
                $label = $items[1];

                $selected = $optval !== NULL && $optval == $value ? 
                            'selected="selected"' : '';

                if ($optval === NULL && $value === 'NULL')
                    $selected = 'selected="selected"';

                if ($selected)
                    return $label;
            }
        }

        return '';
    }

    private function build_select_options_dynamic($func, $optval, $param)
    {
        $ret = array();
        if (! empty($param))
        {
            $select_input_name = $param;
            $value = Arr::get($this->_data, $select_input_name);
            $ret = call_user_func($func, $value);
        }
        else
        {
            $ret = call_user_func($func);
        }



        $options = array();
        foreach ($ret as $id => $name)
        {
            $selected  = $optval !== NULL && $optval == $id ? 
                         'selected="selected"' : '';
                        
            if ($selected)
                return $name;
        }

        return '';
    }


    private function record_group_current_count ()
    {
        $level = $this->_group_level;
        if (! isset($this->_group_count[$level]))
            $this->_group_count[$level] = 0;

        $this->_group_count[$level] += 1;
    }

    private function current_group_suffix ()
    {
        $level = $this->_group_level;
        if ($level == 1)
        {
            return '[]';
        }
        else if ($level == 2)
        {
            $level = $level - 1;
            $index = Arr::get($this->_group_count, $level, 0) - 1;
            return "[$index][]";
        }
        else 
        {
            return '_ERROR_';
        }
    }
}
